import jwt
from django.conf import settings
from django.http import JsonResponse
from django.views import View

from user.models import UserProfile


class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        # token校验
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return JsonResponse({'code': 403, 'error': 'Please login'})
        try:
            payload = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms='HS256')
            try:
                myuser = UserProfile.objects.get(username=payload['username'])
            except  Exception as e:
                return JsonResponse({'code': 403, 'error': 'User does not exist'})
            request.myuser = myuser

        except jwt.ExpiredSignatureError:
            return JsonResponse({'code': 403, 'error': 'Token expired'})
        except jwt.DecodeError:
            return JsonResponse({'code': 403, 'error': 'Token decode error'})
        except jwt.InvalidTokenError:
            return JsonResponse({'code': 403, 'error': 'Token invalid'})

        return super().dispatch(request, *args, **kwargs)